package com.yuyou.fn.timer.task;

import com.alibaba.fastjson.JSONObject;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHander;
import com.xxl.job.core.log.XxlJobLogger;
import com.yuyou.fn.portal.entity.OuterOrder;
import com.yuyou.fn.portal.service.IOuterOrderService;
import com.yuyou.fn.settlement.entity.AccountRecharge;
import com.yuyou.fn.settlement.entity.PayOrder;
import com.yuyou.fn.settlement.service.IAccountRechargeService;
import com.yuyou.fn.settlement.service.IPayOrderService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 检测完成未完成的充值订单
 * Created by lzh on 2018/11/2.
 */
@JobHander(value="CalFinishRechargeOrderTask")
@Component
public class CalFinishRechargeOrderTask extends IJobHandler {


    private static final Logger log = LoggerFactory.getLogger(CalFinishRechargeOrderTask.class);


    @Resource
    private IOuterOrderService outerOrderService;

    @Resource
    private IPayOrderService payOrderService;

    @Resource
    private IAccountRechargeService accountRechargeService;

    @Override
    public ReturnT<String> execute(String... params) throws Exception {

        Date dateNow = new Date();
        Calendar cl = Calendar.getInstance();
        cl.setTime(dateNow);
//		cl.add(Calendar.DAY_OF_YEAR, -1);	//一天
    	cl.add(Calendar.HOUR, -1);	//一小时
//		cl.add(Calendar.MONTH, -1);			//一个月
        Date dateFrom = cl.getTime();

        List<AccountRecharge> accountRechargeList=accountRechargeService.findAccountRecharge(0,dateFrom);
        for(AccountRecharge accountRecharge : accountRechargeList){
            Long accountRechargeId= accountRecharge.getAccountRechargeId();
            PayOrder payOrder=payOrderService.findHadPaidPayOrderByBusId(accountRechargeId);
            if(payOrder!=null){
                Integer status=payOrder.getStatus();
                BigDecimal  amount=payOrder.getAmount();
                if(status==1){
                    try{
                        JSONObject payInfoExt = new JSONObject();
                        payInfoExt.put("transactionNo" ,payOrder.getChannelTransactionNo());
                        payInfoExt.put("channel" ,payOrder.getChannel());
                        accountRechargeService.finishAccountRecharge(accountRechargeId,4,payInfoExt.toJSONString(),null,amount);
                    }catch (Exception e){
                        XxlJobLogger.log("完成充值订单"+accountRechargeId+"发生异常失败" );
                    }
           }
            }

        }
        return ReturnT.SUCCESS ;
    }

}
